package com.songshuai.webapi.jobapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.songshuai.webapi.jobapi.common.enumerations.JobType;
import com.songshuai.webapi.jobapi.common.settings.CacheKeys;
import com.songshuai.webapi.jobapi.dao.crm.ClueInfoMapper;
import com.songshuai.webapi.jobapi.dao.edu.*;
import com.songshuai.webapi.jobapi.dao.productcenter.YixueCourseMapper;
import com.songshuai.webapi.jobapi.dto.base.QueryResponse;
import com.songshuai.webapi.jobapi.dto.edu.CourseScheduleDto;
import com.songshuai.webapi.jobapi.model.crm.ClueInfo;
import com.songshuai.webapi.jobapi.model.crmbase.TpoTeacherInfoWithBLOBs;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentInfoWithBLOBs;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentSchedule;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentScheduleHis;
import com.songshuai.webapi.jobapi.model.edu.TpoStudentShitingInfo;
import com.songshuai.webapi.jobapi.model.productcenter.YixueCourse;
import com.songshuai.webapi.jobapi.service.*;
import com.songshuai.webapi.jobapi.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Administrator
 * @Date: 2018/11/1 0001 19:28
 * @Description:
 */
@Component
@Slf4j
public class CourseScheduleServiceImpl implements CourseScheduleService {

    @Autowired
    StudentScheduleMapper scheduleMapper;

    @Autowired
    ScheduleBaseService scheduleBaseService;

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JobNetPostService postService;

    @Autowired
    SyncLogService syncLogService;

    @Override
    public void SyncCourseSchedule(Boolean isFullDay,String beginTime,String endTime,Boolean isOnlySchedule) {
        HashOperations<String,String,String> operations=redisTemplate.opsForHash();
        String begin=operations.get(CacheKeys.JOB_TIME_CACHE_KEY, String.valueOf(JobType.CourseSchedule.getCode()));
        if(isFullDay||begin==null||begin==""){
            begin= Util.ChangeDateToString(new Date(),"yyyy-MM-dd");
        }
        if(!Util.IsNullAndEmpty(beginTime)){
            begin=beginTime;
        }
//        begin="2018-12-19";
//        isFullDay=false;
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.SECOND,-10);
        String currentTime=Util.ChangeDateToString(calendar.getTime(),"yyyy-MM-dd HH:mm:ss");
        Integer pageSize=50;
        //根据课表更新时间执行
        SyncSchedule(begin,endTime,pageSize,1);
        if(isOnlySchedule==null||!isOnlySchedule){
            //根据签到状态执行
            SyncSchedule(begin,endTime,pageSize,2);
        }
        if(!isFullDay){
            operations.put(CacheKeys.JOB_TIME_CACHE_KEY,String.valueOf(JobType.CourseSchedule.getCode()),currentTime);
        }
    }



    /**
     * 同步正课课表
     * @param begin
     * @param size
     */
    private void SyncSchedule(String begin,String end,Integer size,int updateWay){
        Integer pageIndex=1;
        List<TpoStudentSchedule> studentSchedules=new ArrayList<>();
        if(updateWay==2) {
            studentSchedules = scheduleMapper.getSignStatusChanges(begin,end, (pageIndex - 1) * size, size);
        }else{
            studentSchedules=scheduleMapper.getStudentScheduleByUpdateTime(begin,end,(pageIndex-1)*size,size);
        }

        if(studentSchedules==null||studentSchedules.size()==0){
            return;
        }
        log.info("SyncSchedule Start");
        while (studentSchedules!=null&&studentSchedules.size()>0){
            List<CourseScheduleDto>courseScheduleDtos=new ArrayList<>();
            //获取StudentGuids
            List<String>studentGuids=studentSchedules.stream().map(TpoStudentSchedule::getStudentGuid).filter(c->c!=null&&c!="").distinct().collect(Collectors.toList());

            //获取课程信息
            List<Integer>courseInfoIds=studentSchedules.stream().map(TpoStudentSchedule::getCourseInfoId).filter(c->c!=null&&c>0).distinct().collect(Collectors.toList());
            //获取教师信息
            List<Integer>teacherIds=studentSchedules.stream().map(TpoStudentSchedule::getTeacherId).filter(c->c!=null&&c>0).distinct().collect(Collectors.toList());

            //获取课程信息
            Map<Integer,YixueCourse>courses=scheduleBaseService.getCourseMap(courseInfoIds);
            //获取教师信息
            Map<Integer,String>mapTeachers=userService.getUserNameMaps(teacherIds);

            Map<Integer, TpoTeacherInfoWithBLOBs>mapBaseTeachers=scheduleBaseService.getBaseTeacherInfoMap(teacherIds);

            for(TpoStudentSchedule schedule:studentSchedules){
                CourseScheduleDto scheduleDto=setBaseData(schedule,courses,mapTeachers,mapBaseTeachers);
                if(scheduleDto==null){
                    continue;
                }
                courseScheduleDtos.add(scheduleDto);
            }
            if(courseScheduleDtos.size()>0){
                String listData= JSON.toJSONString(courseScheduleDtos);
                Map<String,String>parms=new HashMap<>();
                parms.put("list",listData);
                QueryResponse<Map<String,Boolean>>res= postService.PostFormData(parms,"course/courseSchedule");

                if(res!=null){
                    syncLogService.AddLogs(JobType.CourseSchedule.getCode(),courseScheduleDtos,res.getData());
                }
            }
            log.info("SyncSchedule Start Page_"+pageIndex);
            pageIndex++;
            if(studentSchedules.size()<size){
                break;
            }

            if(updateWay==2){
                studentSchedules = scheduleMapper.getSignStatusChanges(begin,end,(pageIndex - 1) * size, size);
            }else {
                studentSchedules=scheduleMapper.getStudentScheduleByUpdateTime(begin,end,(pageIndex-1)*size,size);
            }

        }
        log.info("SyncSchedule End");
    }


    @Override
    public void SyncScheduleByLessonIds(List<Integer>lessonIds){
        List<TpoStudentSchedule> studentSchedules=new ArrayList<>();
        studentSchedules = scheduleMapper.getStudentScheduleByLessonIds(lessonIds);
        if(studentSchedules==null||studentSchedules.size()==0){
            return;
        }
        List<CourseScheduleDto>courseScheduleDtos=new ArrayList<>();
        //获取StudentGuids
        List<String>studentGuids=studentSchedules.stream().map(TpoStudentSchedule::getStudentGuid).filter(c->c!=null&&c!="").distinct().collect(Collectors.toList());

        //获取课程信息
        List<Integer>courseInfoIds=studentSchedules.stream().map(TpoStudentSchedule::getCourseInfoId).filter(c->c!=null&&c>0).distinct().collect(Collectors.toList());
        //获取教师信息
        List<Integer>teacherIds=studentSchedules.stream().map(TpoStudentSchedule::getTeacherId).filter(c->c!=null&&c>0).distinct().collect(Collectors.toList());

        //获取课程信息
        Map<Integer,YixueCourse>courses=scheduleBaseService.getCourseMap(courseInfoIds);
        //获取教师信息
        Map<Integer,String>mapTeachers=userService.getUserNameMaps(teacherIds);

        Map<Integer, TpoTeacherInfoWithBLOBs>mapBaseTeachers=scheduleBaseService.getBaseTeacherInfoMap(teacherIds);

        for(TpoStudentSchedule schedule:studentSchedules){
            CourseScheduleDto scheduleDto=setBaseData(schedule,courses,mapTeachers,mapBaseTeachers);
            if(scheduleDto==null){
                continue;
            }
            courseScheduleDtos.add(scheduleDto);
        }
        if(courseScheduleDtos.size()>0){
            String listData= JSON.toJSONString(courseScheduleDtos);
            Map<String,String>parms=new HashMap<>();
            parms.put("list",listData);
            QueryResponse<Map<String,Boolean>>res= postService.PostFormData(parms,"course/courseSchedule");

            if(res!=null){
                syncLogService.AddLogs(JobType.CourseSchedule.getCode(),courseScheduleDtos,res.getData());
            }
        }
    }


    @Override
    public void SyncScheduleByUnit(Integer unit) {
        Integer beginId=0;
        Integer size=50;
        if(unit==null||unit==2){
            return;
        }
        log.info("SyncScheduleByUnit begin");
        List<Integer> lessonIds= scheduleMapper.selectLessonIdsByUnit(beginId,unit,size);
        while (lessonIds!=null&&lessonIds.size()>0){
            SyncScheduleByLessonIds(lessonIds);
            beginId=lessonIds.get(lessonIds.size()-1);
            if(lessonIds.size()<size){
                break;
            }
            lessonIds= scheduleMapper.selectLessonIdsByUnit(beginId,unit,size);
        }
        log.info("SyncScheduleByUnit end");
    }

    @Override
    public void RemoveScheduleByLessonIds(List<Integer> lessonIds,Long gw_id){
        List<TpoStudentSchedule> studentSchedules=new ArrayList<>();
        studentSchedules = scheduleMapper.getStudentScheduleByLessonIds(lessonIds);
        if(studentSchedules==null||studentSchedules.size()==0||gw_id==null||gw_id==0){
            return;
        }
        List<CourseScheduleDto>courseScheduleDtos=new ArrayList<>();

        for(TpoStudentSchedule schedule:studentSchedules){
            CourseScheduleDto scheduleDto=setBaseData(schedule,null,null,null);
            if(scheduleDto==null){
                continue;
            }
            scheduleDto.setUser_id(gw_id+"");
            scheduleDto.setStatus("1");
            courseScheduleDtos.add(scheduleDto);
        }
        if(courseScheduleDtos.size()>0){
            String listData= JSON.toJSONString(courseScheduleDtos);
            Map<String,String>parms=new HashMap<>();
            parms.put("list",listData);
            QueryResponse<Map<String,Boolean>>res= postService.PostFormData(parms,"course/courseSchedule");

            if(res!=null){
                syncLogService.AddLogs(JobType.CourseSchedule.getCode(),courseScheduleDtos,res.getData());
            }
        }
    }

    @Override
    public void changeGwId(Long oldId, Long newId,Boolean isSyncNew) {
        List<Integer>lessonIds=scheduleMapper.selectLessonIdsByGwId(newId);
        if(lessonIds==null||lessonIds.size()==0){
            return;
        }
        if(isSyncNew==null){
            isSyncNew=false;
        }
        Integer pageSize=50;
        Integer arrSize=lessonIds.size();
        int md=arrSize/pageSize;
        if(arrSize%pageSize>0){
            md=md+1;
        }
        for(int i=0;i<md;i++){
            System.out.println("pageIndex:"+i);
            List<Integer>subIds=new ArrayList<>();
            if(i==md-1){
                subIds=lessonIds.subList(i*50,lessonIds.size());
            }else{
                subIds=lessonIds.subList(i*50,(i+1)*50);
            }
            if(!isSyncNew){
                RemoveScheduleByLessonIds(subIds,oldId);
            }
            SyncScheduleByLessonIds(subIds);
        }
    }


    /**
     *
     * @param schedule
     * @param courseMap
     * @return
     */
    private CourseScheduleDto setBaseData(TpoStudentSchedule schedule,Map<Integer,YixueCourse>courseMap,Map<Integer,String>teacherMaps,Map<Integer, TpoTeacherInfoWithBLOBs>baseTeachers) {
        CourseScheduleDto retData=null;
        if(schedule==null||schedule.getGw_id()==null||schedule.getGw_id().length()==0||schedule.getGw_id().equals("0")){
            return retData;
        }
        retData=new CourseScheduleDto();
        Integer signStatus=Util.get_old_qian_dao(schedule.getSignStatus());
        retData.setAttendance_status(signStatus==null?"0":String.valueOf(signStatus));
        retData.setEnd_time(schedule.getEndTime()==null?"":Util.ChangeDateToString(schedule.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        retData.setLesson_id(String.valueOf(schedule.getId()));
        retData.setSchedule_num(schedule.getScheduleIndex()==null?"0":String.valueOf(schedule.getScheduleIndex()));
        retData.setSchedule_total(schedule.getScheduleTotal()==null?"0":String.valueOf(schedule.getScheduleTotal()));
        retData.setStart_time(Util.ChangeDateToString(schedule.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
        retData.setUnit(schedule.getUnit()==null?"0":String.valueOf(schedule.getUnit()));
        retData.setCrm_teacher_id(schedule.getTeacherId()==null?"0":String.valueOf(schedule.getTeacherId()));
        retData.setCrm_course_id(schedule.getCourseInfoId()==null?"0":String.valueOf(schedule.getCourseInfoId()));
        retData.setCrm_user_id(schedule.getClueGuid()==null?"0":schedule.getClueGuid());
        retData.setUser_id(schedule.getGw_id()==null?"0":schedule.getGw_id());
        retData.setCourse_type("20");
        retData.setTeacher_id("0");
        retData.setTeacher_name("");
        retData.setStatus("0");
        retData.setCrm_teacher_name("");
        retData.setCourse_id("0");
        retData.setGw_course_id("0");
        retData.setSubject_id("0");
        if(teacherMaps!=null&&schedule.getTeacherId()!=null){
            retData.setCrm_teacher_name(teacherMaps.getOrDefault(schedule.getTeacherId(),""));
        }
        YixueCourse yixueCourse=null;
        if(courseMap!=null){
            yixueCourse=courseMap.getOrDefault(schedule.getCourseInfoId(),null);
        }
        if(yixueCourse!=null){
            retData.setCourse_id(yixueCourse.getHt_id()==null?"0":String.valueOf(yixueCourse.getHt_id()));
            retData.setGw_course_id(yixueCourse.getGw_id()==null?"0":String.valueOf(yixueCourse.getGw_id()));
            retData.setSubject_id(yixueCourse.getCsubject()==null?"0":String.valueOf(yixueCourse.getCsubject()));
        }
        if(baseTeachers!=null&&schedule.getTeacherId()!=null){
            TpoTeacherInfoWithBLOBs baseTeacher=baseTeachers.getOrDefault(schedule.getTeacherId(),null);
            if(baseTeacher!=null){
                retData.setTeacher_id(baseTeacher.getTwxId()==null?"0":String.valueOf(baseTeacher.getTwxId()));
                retData.setTeacher_name(baseTeacher.getTwxAccount()==null?"":baseTeacher.getTwxAccount());
            }
        }

        return retData;
    }



}
